package cn.com.netedge.iot.frontend.datasave.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

@Configuration("feDataSaveConfig")
public class MybatisConfig {
    private static Logger logger = LoggerFactory.getLogger(MybatisConfig.class);

    @Bean
    public DataSource dataSource(@Value("${jdbc.driver-class-name}") String driverClassName, @Value("${jdbc.url}") String url,
                                 @Value("${jdbc.username}") String username, @Value("${jdbc.password}") String password) {
        DruidDataSource dataSource = new DruidDataSource();
        try {
            dataSource.setDriverClassName(driverClassName);
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
        } catch (Exception e) {
            logger.error("get datasource error.", e);
        }
        return dataSource;

    }

    @Bean
    public SqlSessionFactory mybatisMasterSqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        List<Resource> resourceList = new ArrayList<>();
        Resource[] resources = resolver.getResources("classpath:mapper/**/*Mapper.xml");
        if(resources != null && resources.length >0) {
            for(Resource item:resources) {
                resourceList.add(item);
            }
        }
        resources = resourceList.toArray(new Resource[0]);
        bean.setMapperLocations(resources);

        return bean.getObject();
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mScannerConfigurer = new MapperScannerConfigurer();
        mScannerConfigurer.setSqlSessionFactoryBeanName("mybatisMasterSqlSessionFactory");
        mScannerConfigurer.setBasePackage("cn.com.netedge.iot.fe.datasave.dao");
        return mScannerConfigurer;
    }
}
